//
//  BSKClassifySettingViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/15.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import <AVOSCloud/AVOSCloud.h>

#import "BSKClassifySettingViewController.h"
#import "UIView+SDAutoLayout.h"
#import "BSKTheme.h"
#import "BSKCurrentTheme.h"
#import "BSKconsts.h"
#import "BSKImageCollectionViewCell.h"
#import "BSKImagePikerController.h"
#import "BSKDBManager.h"
#import "AFNetworking.h"
#import "BSKStringCheck.h"
#import "UIViewController+BSKToast.h"
#import "IQKeyboardManager.h"

@interface BSKClassifySettingViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate>

@property (strong, nonatomic) UIView *navView;
@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIScrollView *contentScrollView;
@property (strong, nonatomic) UICollectionView *imagesCollection;
@property (strong, nonatomic) UITextField *classifyTextField;
@property (strong, nonatomic) UISwitch *isSecretSwitch;
@property (strong, nonatomic) UILabel *passwordLabel;
@property (strong, nonatomic) UITextField *passwordTextField;
@property (strong, nonatomic) UILabel *surePswLabel;
@property (strong, nonatomic) UITextField *surePasswordTextField;
@property (assign, nonatomic) BOOL secretMode;// 加密状态
@property (strong, nonatomic) UIColor *currentColor;// 字体颜色
@property (strong, nonatomic) UIColor *currentBgColor;// 文本框背景色
@property (strong, nonatomic) UIColor *currentBorderColor;// 文本框边框色
@property (assign, nonatomic) NSInteger flag;
@property (strong, nonatomic) NSMutableArray *dataSource;
@property (nonatomic, strong) BSKDBManager * magager;//数据库管理对象
@property (nonatomic, strong) NSString *picFileName;
@property (nonatomic, strong) NSString *typeID;
@property (nonatomic, strong) NSString *userID;
@property (nonatomic, strong) UIImage *customPic;
@property (nonatomic, strong) UIButton *saveButton;
@property (strong, nonatomic) UIVisualEffectView * coverview;
@property (strong, nonatomic) UIImageView *imageView ;

@end

@implementation BSKClassifySettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.9525 green:0.9525 blue:0.9525 alpha:1.0];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.typeID = [NSString stringWithFormat:@"%ld", (long)([NSDate date].timeIntervalSince1970 * 100)];
    _magager = [[BSKDBManager alloc]init];
    [_magager openDataBase:@"notedatabase.db"];
    [self initializeDataSource];
    [self initializeUserInterface];
    [self refreshCurrentImage];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _flag = 0;
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (_flag == 0) {
        CGFloat contentHeight = (self.view.width - 40) / 3 * 16 / 9 + 30 + 20 + 20 + 25 + 20 + 40 + 20 + 30 + 20 + 30;
        if (self.contentScrollView.height_sd <= contentHeight) {
            self.contentScrollView.contentSize = CGSizeMake(self.view.width, contentHeight);
        } else {
            self.contentScrollView.contentSize = self.contentScrollView.size_sd;
        }
        _flag = 1;
    }
}

- (void)initializeDataSource {
    self.picFileName = @"localHost://paper1";
    self.userID = @"null";
    if ([AVUser currentUser]) {
        self.userID = [AVUser currentUser].objectId;
    }
    if (self.type) {
        self.typeID = self.type.typeID;
        self.secretMode = self.type.secretMode;
        self.picFileName = self.type.pictureFileName;
    }
    self.currentColor = [UIColor clearColor];
    self.currentBgColor = [UIColor clearColor];
    self.currentBorderColor = [UIColor clearColor];
    if (self.secretMode) {
        self.currentColor = [UIColor whiteColor];
        self.currentBgColor = [UIColor whiteColor];
        self.currentBorderColor = [UIColor grayColor];
    }
    self.dataSource = [NSMutableArray array];
    [self.dataSource addObjectsFromArray:@[@"paper1",@"paper2",@"water.jpg",@"autumn.jpg",@"black.jpg", @"selectPicture"]];
}
- (void)refreshCurrentImage {
    if ([[self.picFileName substringToIndex:12] isEqualToString:@"localHost://"]) {
        [BSKCurrentTheme curentTheme].themeImage = [UIImage imageNamed:[self.picFileName substringFromIndex:12]];
    }else{
        NSString * typeImageDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSData * imageData = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",typeImageDirPath,self.picFileName]];
        [BSKCurrentTheme curentTheme].themeImage = [UIImage imageWithData:imageData];
    }
    self.navView.backgroundColor = [UIColor clearColor];
    self.imageView.image = [BSKCurrentTheme curentTheme].themeImage;
    self.saveButton.backgroundColor = [BSKCurrentTheme curentTheme].themeColor;
    
}
- (void)initializeUserInterface {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake((self.view.width - 40) / 3, (self.view.width - 40) / 3 * 16 / 9);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    
    
    UIBlurEffect * efect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.coverview  = [[UIVisualEffectView alloc] initWithEffect:efect];
    self.imageView  = [[UIImageView alloc] initWithImage:[BSKTheme curentTheme].themeImage];
    self.coverview.frame = self.view.bounds;
    self.imageView.frame = self.view.bounds;
    [self.view addSubview:self.imageView];
    //    [self.view addSubview:self.coverview];
    UIView *bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgView.backgroundColor = [UIColor blackColor];
    bgView.alpha = 0.4;
    [self.view addSubview:bgView];
    self.navView = [[UIView alloc] init];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.titleLabel = [[UILabel alloc] init];
    self.contentScrollView = [[UIScrollView alloc] init];
    UILabel *imageLabel = [[UILabel alloc] init];
    self.imagesCollection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    UILabel *classifyLabel = [[UILabel alloc] init];
    self.classifyTextField = [[UITextField alloc] init];
    UILabel *isSecretLabel = [[UILabel alloc] init];
    self.isSecretSwitch = [[UISwitch alloc] init];
    self.passwordLabel = [[UILabel alloc] init];
    self.passwordTextField = [[UITextField alloc] init];
    self.surePswLabel = [[UILabel alloc] init];
    self.surePasswordTextField = [[UITextField alloc] init];
    self.saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    
    [self.view addSubview:self.navView];
    [self.navView addSubview:self.backButton];
    [self.navView addSubview:self.titleLabel];
    [self.view addSubview:self.contentScrollView];
    [self.contentScrollView addSubview:imageLabel];
    [self.contentScrollView addSubview:self.imagesCollection];
    [self.contentScrollView addSubview:classifyLabel];
    [self.contentScrollView addSubview:self.classifyTextField];
    [self.contentScrollView addSubview:isSecretLabel];
    [self.contentScrollView addSubview:self.isSecretSwitch];
    [self.contentScrollView addSubview:self.passwordLabel];
    [self.contentScrollView addSubview:self.passwordTextField];
    [self.contentScrollView addSubview:self.surePswLabel];
    [self.contentScrollView addSubview:self.surePasswordTextField];
    [self.view addSubview:self.saveButton];
    
    self.navView.sd_layout.topEqualToView(self.view)
    .widthRatioToView(self.view, 1)
    .heightIs(StatusBarHeight + NavigationBarHeight);
    //    self.navView.backgroundColor = [BSKTheme curentTheme].themeColor;
    
    self.backButton.sd_layout.topSpaceToView(self.navView, StatusBarHeight + 5)
    .leftSpaceToView(self.navView, 5)
    .widthIs(NavigationBarHeight - 10)
    .heightIs(NavigationBarHeight - 10);
    self.backButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
    [self.backButton setImage:[UIImage imageNamed:@"back" ] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.titleLabel.sd_layout.centerXIs(self.view.centerX)
    .centerYEqualToView(self.backButton);
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = @"分类设置";
    [self.titleLabel sizeToFit];
    
    self.contentScrollView.sd_layout.topSpaceToView(self.navView, 0)
    .leftEqualToView(self.view)
    .bottomSpaceToView(self.view, 80)
    .rightEqualToView(self.view);
    self.contentScrollView.showsVerticalScrollIndicator = NO;
    self.contentScrollView.bounces = NO;
    self.contentScrollView.contentSize = self.contentScrollView.size;
    
    imageLabel.sd_layout.topSpaceToView(self.contentScrollView, 5)
    .leftSpaceToView(self.contentScrollView, 10)
    .heightIs(20)
    .widthIs(100);
    imageLabel.text = @"封面图片";
    imageLabel.font = [UIFont systemFontOfSize:15];
    imageLabel.textColor = [UIColor whiteColor];
    
    self.imagesCollection.sd_layout.topSpaceToView(imageLabel, 5)
    .leftSpaceToView(self.contentScrollView, 0)
    .heightIs((self.view.width - 40) / 3 * 16 / 9)
    .rightSpaceToView(self.contentScrollView, 0);
    self.imagesCollection.backgroundColor = [UIColor clearColor];
    self.imagesCollection.delegate = self;
    self.imagesCollection.dataSource = self;
    self.imagesCollection.showsHorizontalScrollIndicator = NO;
    self.imagesCollection.bounces = NO;
    self.imagesCollection.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
    [self.imagesCollection registerClass:[BSKImageCollectionViewCell class]
              forCellWithReuseIdentifier:@"imageCell"];
    
    classifyLabel.sd_layout.topSpaceToView(self.imagesCollection, 20)
    .leftSpaceToView(self.contentScrollView, 30)
    .heightIs(20)
    .widthIs(70);
    classifyLabel.text = @"分类名称";
    classifyLabel.font = [UIFont systemFontOfSize:15];
    classifyLabel.textColor = [UIColor whiteColor];
    
    self.classifyTextField.sd_layout.centerYEqualToView(classifyLabel)
    .leftSpaceToView(classifyLabel, 0)
    .heightIs(40)
    .rightSpaceToView(self.contentScrollView, 30);
    self.classifyTextField.delegate = self;
    self.classifyTextField.layer.cornerRadius = 10;
    self.classifyTextField.layer.masksToBounds = YES;
    self.classifyTextField.layer.borderColor = [UIColor grayColor].CGColor;
    self.classifyTextField.layer.borderWidth = 1;
    self.classifyTextField.backgroundColor = [UIColor whiteColor];
    self.classifyTextField.textColor = [UIColor grayColor];
    self.classifyTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.classifyTextField.textAlignment = NSTextAlignmentCenter;
    self.classifyTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.classifyTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    
    UILabel * leftView = [[UILabel alloc] initWithFrame:CGRectMake(0,0,5,0)];
    self.classifyTextField.leftView = leftView;
    self.classifyTextField.leftViewMode = UITextFieldViewModeAlways;
    self.classifyTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    isSecretLabel.sd_layout.topSpaceToView(classifyLabel, 25)
    .leftSpaceToView(self.contentScrollView, 30)
    .heightIs(20)
    .widthIs(70);
    isSecretLabel.text = @"是否加密";
    isSecretLabel.font = [UIFont systemFontOfSize:15];
    isSecretLabel.textColor = [UIColor whiteColor];
    
    self.isSecretSwitch.sd_layout.centerYEqualToView(isSecretLabel)
    .rightSpaceToView(self.contentScrollView, 30);
    self.isSecretSwitch.backgroundColor = [UIColor lightGrayColor];
    self.isSecretSwitch.layer.cornerRadius = 15;
    self.isSecretSwitch.layer.masksToBounds = YES;
    [self.isSecretSwitch setTintColor:[UIColor lightGrayColor]];
    [self.isSecretSwitch setThumbTintColor:[UIColor whiteColor]];
    [self.isSecretSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    
    self.passwordLabel.sd_layout.topSpaceToView(isSecretLabel, 40)
    .leftSpaceToView(self.contentScrollView, 50)
    .heightIs(20)
    .widthIs(70);
    self.passwordLabel.text = @"密码";
    self.passwordLabel.font = [UIFont systemFontOfSize:15];
    self.passwordLabel.textColor = self.currentColor;
    
    self.passwordTextField.sd_layout.centerYEqualToView(self.passwordLabel)
    .leftSpaceToView(self.passwordLabel, 0)
    .rightSpaceToView(self.contentScrollView, 50)
    .heightIs(40);
    self.passwordTextField.delegate = self;
    self.passwordTextField.backgroundColor = self.currentBgColor;
    self.passwordTextField.textColor = [UIColor grayColor];
    self.passwordTextField.layer.cornerRadius = 10;
    self.passwordTextField.layer.masksToBounds = YES;
    self.passwordTextField.secureTextEntry = YES;
    self.passwordTextField.layer.borderColor = self.currentBorderColor.CGColor;
    self.passwordTextField.enabled = self.secretMode;
    self.passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.passwordTextField.layer.borderWidth = 1;
    UIView *pswLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 0)];
    self.passwordTextField.leftView = pswLeftView;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    self.passwordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    self.surePswLabel.sd_layout.topSpaceToView(self.passwordLabel, 30)
    .leftSpaceToView(self.contentScrollView, 50)
    .heightIs(20)
    .widthIs(70);
    self.surePswLabel.text = @"确认密码";
    self.surePswLabel.font = [UIFont systemFontOfSize:15];
    self.surePswLabel.textColor = self.currentColor;
    
    self.surePasswordTextField.sd_layout.centerYEqualToView(self.surePswLabel)
    .leftSpaceToView(self.passwordLabel, 0)
    .rightSpaceToView(self.contentScrollView, 50)
    .heightIs(40);
    self.surePasswordTextField.delegate = self;
    self.surePasswordTextField.backgroundColor = self.currentBgColor;
    self.surePasswordTextField.textColor = [UIColor grayColor];
    self.surePasswordTextField.layer.cornerRadius = 10;
    self.surePasswordTextField.layer.masksToBounds = YES;
    self.surePasswordTextField.secureTextEntry = YES;
    self.surePasswordTextField.layer.borderColor = self.currentBorderColor.CGColor;
    self.surePasswordTextField.layer.borderWidth = 1;
    self.surePasswordTextField.enabled = self.secretMode;
    self.surePasswordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.surePasswordTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    UIView *surePswLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 0)];
    self.surePasswordTextField.leftView = surePswLeftView;
    self.surePasswordTextField.leftViewMode = UITextFieldViewModeAlways;
    self.surePasswordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    self.saveButton.sd_layout.bottomSpaceToView(self.view, 15)
    .leftSpaceToView(self.view, 30)
    .rightSpaceToView(self.view, 30)
    .heightIs(50);
    self.saveButton.backgroundColor = [BSKTheme curentTheme].themeColor;
    self.saveButton.layer.cornerRadius = 10;
    self.saveButton.layer.masksToBounds = YES;
    [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [self.saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.saveButton addTarget:self action:@selector(saveButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.isSecretSwitch.on = self.secretMode;
    self.isSecretSwitch.selected = self.secretMode;
    self.classifyTextField.text = self.type.typeName;
    self.passwordTextField.text = self.type.password;
    self.surePasswordTextField.text = self.type.password;
}

- (void)backButtonAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)saveButtonAction:(UIButton *)sender {
    sender.enabled = NO;
    // 本地设置
    if (![self textFieldCheck:self.classifyTextField]) {
        sender.enabled = YES;
    } else if (self.secretMode) {
        if (![self textFieldCheck:_passwordTextField]) {
            sender.enabled = YES;
        } else if (![self textFieldCheck:_surePasswordTextField]) {
            sender.enabled = YES;
        } else if (_status) {
            [self savePicFile];
            [_magager insertDataToTable:@"type"
                               Columnns:@[@[@"typeID",	         self.typeID],
                                          @[@"userID",		     self.userID],
                                          @[@"typeName",	     self.classifyTextField.text],
                                          @[@"pictureFileName", self.picFileName],
                                          @[@"objectID",	     @"null"],
                                          @[@"updateTime",	[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]],//上次修改时间
                                          @[@"secretMode",	     [NSNumber numberWithBool:self.secretMode]],
                                          @[@"password",	     self.passwordTextField.text],
                                          ]];
            [self.navigationController MakeToast:@"保存成功！" WithTime:1.5];
            [[NSNotificationCenter defaultCenter]postNotificationName:BSKtypeListChangeNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self savePicFile];
            [_magager updateDataToTable:@"type"
                               Columnns:@[@[@"typeName",	     self.classifyTextField.text],
                                          @[@"pictureFileName",  self.picFileName],
                                          @[@"updateTime",	[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]],//上次修改时间
                                          @[@"secretMode",	     [NSNumber numberWithBool:self.secretMode]],
                                          @[@"password",	     self.passwordTextField.text]]
                              condition:[NSString stringWithFormat:@"typeID = '%@'", self.typeID]];
            [self.navigationController MakeToast:@"修改成功！" WithTime:1.5];
            [[NSNotificationCenter defaultCenter]postNotificationName:BSKtypeListChangeNotification object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else if (_status) {
        [self savePicFile];
        [_magager insertDataToTable:@"type"
                           Columnns:@[@[@"typeID",	     self.typeID],
                                      @[@"userID",		 self.userID],
                                      @[@"typeName",	    self.classifyTextField.text],
                                      @[@"updateTime",	[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]],//上次修改时间
                                      @[@"pictureFileName", self.picFileName],
                                      @[@"objectID",	     @"null"],
                                      @[@"secretMode",	 [NSNumber numberWithBool:self.secretMode]],
                                      @[@"password",	self.passwordTextField.text],
                                      ]];
        [self.navigationController MakeToast:@"保存成功！" WithTime:1.5];
        [[NSNotificationCenter defaultCenter]postNotificationName:BSKtypeListChangeNotification object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self savePicFile];
        [_magager updateDataToTable:@"type"
                           Columnns:@[@[@"typeName",	     self.classifyTextField.text],
                                      @[@"pictureFileName", self.picFileName],
                                      @[@"updateTime",	[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]]],//上次修改时间
                                      @[@"secretMode",	     [NSNumber numberWithBool:self.secretMode]],
                                      @[@"password",	     self.passwordTextField.text]]
                          condition:[NSString stringWithFormat:@"typeID = '%@'", self.typeID]];
        [self.navigationController MakeToast:@"修改成功！" WithTime:1.5];
        [[NSNotificationCenter defaultCenter]postNotificationName:BSKtypeListChangeNotification object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)savePicFile {
    if (![[self.picFileName substringToIndex:12] isEqualToString:@"localHost://%@"] && (self.customPic != nil)) {
        NSData *imagedata = UIImageJPEGRepresentation(self.customPic, 1.0);
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, self.picFileName]]) {
            [fileManager createFileAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, self.picFileName] contents:imagedata attributes:nil];
        } else {
            NSError *error = [[NSError alloc] init];
            if ([fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, self.picFileName] error:&error]) {
                [fileManager createFileAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, self.picFileName] contents:imagedata attributes:nil];
            }
        }
    }
}
- (void)switchAction:(UISwitch *)sender {
	[self.view endEditing:YES];
    sender.selected = !sender.selected;
    self.secretMode = sender.selected;
    self.currentColor = [UIColor clearColor];
    self.currentBgColor = [UIColor clearColor];
    self.currentBorderColor = [UIColor clearColor];
    if (self.secretMode) {
        self.currentColor = [UIColor whiteColor];
        self.currentBgColor = [UIColor whiteColor];
        self.currentBorderColor = [UIColor grayColor];
    } else {
        self.passwordTextField.text = @"";
        self.surePasswordTextField.text = @"";
    }
    self.passwordLabel.textColor = self.currentColor;
    self.passwordTextField.enabled = self.secretMode;
    self.passwordTextField.backgroundColor = self.currentBgColor;
    self.passwordTextField.layer.borderColor = self.currentBorderColor.CGColor;
    self.surePswLabel.textColor = self.currentColor;
    self.surePasswordTextField.enabled = self.secretMode;
    self.surePasswordTextField.backgroundColor = self.currentBgColor;
    self.surePasswordTextField.layer.borderColor = self.currentBorderColor.CGColor;
}
- (void)selectImageAction {
    UIAlertController *alertControler = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //防止循环引用
    __weak typeof(self) weakSelf = self;
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf selectAlbum];
    }];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [weakSelf takePhoto];
    }];
    
    [alertControler addAction:cancelAction];
    [alertControler addAction:albumAction];
    [alertControler addAction:takePhotoAction];
    [self presentViewController:alertControler animated:YES completion:nil];
    
}
//相册选择照片
- (void)selectAlbum {
    // 跳到图片选择器
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.delegate = self;
    // 资源类型
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    // 是否允许编辑
    imagePicker.allowsEditing = NO;
    
    [self presentViewController:imagePicker animated:YES completion:nil];
    [self.imagesCollection reloadData];
}
//拍照
- (void)takePhoto {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误！无法连接到相机" message:@"请检查您的相关设置或者摄像头" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:sureAction];
        [self presentViewController:alert animated:YES completion:nil];
        
        return;
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    //资源类型
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //是否允许编辑
    imagePicker.allowsEditing = NO;
    
    [self presentViewController:imagePicker animated:YES completion:nil];
    [self.imagesCollection reloadData];
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    BSKImagePikerController *customImagePicker =  [[BSKImagePikerController alloc] initWithImage:info[UIImagePickerControllerOriginalImage] toSize:[UIScreen mainScreen].bounds.size backBlock:^(UIImage *image) {
        self.customPic = image;
        NSString *fileName = [NSString stringWithFormat:@"%@%@.jpg", _typeID, self.userID];
        _picFileName = fileName;
        [BSKCurrentTheme curentTheme].themeImage = self.customPic;
        
        self.navView.backgroundColor = [UIColor clearColor];
        self.imageView.image = [BSKCurrentTheme curentTheme].themeImage;
        self.saveButton.backgroundColor = [BSKCurrentTheme curentTheme].themeColor;
        [_imagesCollection reloadData];
    }];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self presentViewController:customImagePicker animated:YES completion:nil];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BSKImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:self.dataSource[indexPath.row]];
    cell.backgroundColor = [UIColor whiteColor];
    if ([self.picFileName isEqualToString:[NSString stringWithFormat:@"localHost://%@", _dataSource[indexPath.row]]]) {
        cell.selectedImageView.hidden = NO;
    } else {
        cell.selectedImageView.hidden = YES;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.dataSource.count - 1) {
        self.picFileName = [NSString stringWithFormat:@"localHost://%@", self.dataSource[indexPath.row]];
        [self refreshCurrentImage];
        [collectionView reloadData];
    } else {
        // 跳到图片选择器
        [self selectImageAction];
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.passwordTextField || textField == self.surePasswordTextField) {
        if (range.location > 11) {
            return NO;
        }
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField endEditing:YES];
    if ([self textFieldCheck:textField]) {
        if (textField == self.passwordTextField) {
            [self.surePasswordTextField becomeFirstResponder];
        } else {
            [self.view endEditing:YES];
        }
    }
    return YES;
}
- (BOOL)textFieldCheck:(UITextField *)textField {
    if (textField == self.classifyTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"请输入分类名！" WithTime:1.5];
            return NO;
        }  else if (![BSKStringCheck validateNickname:textField.text]) {
            [self MakeToast:@"分类名过长" WithTime:1.5];
            return NO;
        }
    }
    if (textField == self.passwordTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"密码不能为空！" WithTime:1.5];
            return NO;
        } else if (![BSKStringCheck validateShortPassword:textField.text]) {
            [self MakeToast:@"请输入3~12位由拼音、字母、下划线组成的密码！" WithTime:1.5];
            return NO;
        }
    }
    
    if (textField == self.surePasswordTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"请确认密码！" WithTime:1.5];
            return NO;
        } else if (![textField.text isEqualToString:self.passwordTextField.text]) {
            [self MakeToast:@"前后密码不一致！" WithTime:1.5];
            return NO;
        }
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
@end
